package com.wgt.startx.util;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

/**
 * 反射工具类
 * Created by wgt on 2017/7/30.
 */
public final class ReflectionUtil {
    private static Logger log = LoggerFactory.getLogger(ReflectionUtil.class);

    /**
     * 创建对象实例
     * @param clazz
     * @return
     */
    public static Object instanceObj(Class<?> clazz){
        Object instance ;
        try {
            instance = clazz.newInstance();
        } catch (Exception e) {
            log.error("new Instance failure:{}",e);
            throw new RuntimeException(e);
        }
        return instance;
    }

    /**
     * 调用方法
     * @return
     */
    public static Object invokeMethod(Object target, Method method, Object...args){
        Object result;
        try {
            method.setAccessible(true);
            result = method.invoke(target,args);
        } catch (Exception e) {
            log.error("invaoke Method failure:{}",e);
            throw new RuntimeException(e);
        }
        return result;
    }

    /**
     * 设置变量值
     * @param target
     * @param field
     * @param args
     */
    public static void setField(Object target, Field field,Object...args){
        try {
            field.setAccessible(true);
            field.set(target,args);
        }catch (Exception e){
            log.error("invoke method failure:{}",e);
            throw new RuntimeException(e);
        }
    }
}
